<template>
  <div class="article-detail">
    <Header />
    <Breadcrumb :items="breadcrumbItems" />
    
    <div class="article-container">
      <div v-if="loading" class="text-center py-5">
        <div class="spinner-border" role="status">
          <span class="sr-only">加载中...</span>
        </div>
      </div>
      
      <div v-else class="article-wrapper">
        <!-- 文章主体 -->
        <div class="article-main">
          <div class="article-header">
            <h1 class="article-title">{{ article.title }}</h1>
            
            <div class="article-meta">
              <span class="meta-item"><i class="icon-user"></i>{{ article.author || '未知' }}</span>
              <span class="meta-item"><i class="icon-source"></i>{{ article.source || '本站' }}</span>
              <span class="meta-item"><i class="icon-date"></i>{{ formatDate(article.publishTime) }}</span>
              <span class="meta-item"><i class="icon-view"></i>{{ article.viewCount || 0 }}次阅读</span>
            </div>
          </div>
          
          <div v-if="article.coverImage" class="article-cover">
            <img :src="article.coverImage" :alt="article.title" class="cover-image">
          </div>
          
          <div class="article-body" v-html="article.content"></div>
          
          <div class="article-footer">
            <div class="article-tags">
              <span v-for="tag in article.keywords.split(',')" :key="tag" class="tag-item">
                {{ tag }}
              </span>
            </div>
          </div>
        </div>
        
        <!-- 评论区域 -->
        <div class="comment-section">
          <h3 class="comment-title"><span>评论</span></h3>
          
          <!-- 评论列表 -->
          <div v-if="comments.length > 0" class="comment-list">
            <div v-for="comment in comments" :key="comment.id" class="comment-item">
              <div class="comment-avatar">
                <span class="avatar-text">{{ comment.userName.charAt(0).toUpperCase() }}</span>
              </div>
              <div class="comment-content">
                <div class="comment-header">
                  <span class="comment-user">{{ comment.userName }}</span>
                  <span class="comment-time">{{ formatDate(comment.createTime) }}</span>
                </div>
                <div class="comment-text">{{ comment.content }}</div>
              </div>
            </div>
          </div>
          <div v-else class="no-comment">
            <i class="icon-comment"></i>
            <p>暂无评论，快来抢沙发吧~</p>
          </div>
          
          <!-- 评论表单 -->
          <div class="comment-form">
            <h4 class="form-title">发表评论</h4>
            <form @submit.prevent="submitComment">
              <div class="form-group">
                <textarea 
                  v-model="newComment.content" 
                  class="form-textarea" 
                  placeholder="写下你的想法..." 
                  required
                ></textarea>
              </div>
              <div class="form-row">
                <div class="form-col">
                  <input 
                    v-model="newComment.userName" 
                    type="text" 
                    class="form-input" 
                    placeholder="昵称" 
                    required
                  >
                </div>
                <div class="form-col">
                  <input 
                    v-model="newComment.email" 
                    type="email" 
                    class="form-input" 
                    placeholder="邮箱"
                  >
                </div>
                <div class="form-col">
                  <button type="submit" class="submit-btn">
                    提交评论
                  </button>
                </div>
              </div>
            </form>
          </div>
        </div>
      </div>
    </div>
    
    <Footer />
  </div>
</template>

<script>
import Header from '@/components/Header'
import Footer from '@/components/Footer'
import Breadcrumb from '@/components/Breadcrumb'
import { getArticleById, increaseViewCount } from '@/api/article'
import { getCategoryById } from '@/api/category'
import { getCommentsByArticleId, addComment } from '@/api/comment'

export default {
  name: 'ArticleDetail',
  components: {
    Header,
    Footer,
    Breadcrumb
  },
  props: {
    id: {
      type: [String, Number],
      required: true
    }
  },
  data() {
    return {
      article: {},
      loading: false,
      breadcrumbItems: [],
      comments: [],
      newComment: {
        articleId: this.id,
        userName: '',
        email: '',
        content: ''
      }
    }
  },
  watch: {
    id: {
      immediate: true,
      handler(newVal) {
        if (newVal) {
          this.fetchArticleData()
        }
      }
    }
  },
  methods: {
    async fetchArticleData() {
      this.loading = true
      try {
        const [articleRes, viewRes] = await Promise.all([
          getArticleById(this.id),
          increaseViewCount(this.id)
        ])
        
        this.article = articleRes.data
        await this.generateBreadcrumb()
        await this.fetchComments()
      } catch (error) {
        console.error('获取文章数据失败:', error)
        this.$router.replace('/404')
      } finally {
        this.loading = false
      }
    },
    async generateBreadcrumb() {
      const items = [{ text: '首页', to: '/' }]
      
      try {
        if (this.article.categoryId) {
          const categoryRes = await getCategoryById(this.article.categoryId)
          const category = categoryRes.data
          
          items.push({
            text: category.categoryName,
            to: `/category/${category.categoryId}`
          })
        }
      } catch (error) {
        console.error('获取栏目信息失败:', error)
      }
      
      items.push({
        text: this.article.title,
        active: true
      })
      
      this.breadcrumbItems = items
    },
    async fetchComments() {
      try {
        const res = await getCommentsByArticleId(this.id)
        this.comments = res.data
      } catch (error) {
        console.error('获取评论失败:', error)
      }
    },
    async submitComment() {
      try {
        await addComment(this.newComment)
        alert('评论提交成功')
        this.newComment.content = ''
        await this.fetchComments()
      } catch (error) {
        console.error('提交评论失败:', error)
        alert('评论提交失败，请稍后再试')
      }
    },
    formatDate(dateStr) {
      if (!dateStr) return '未知'
      const date = new Date(dateStr)
      return date.getFullYear() + '-' + 
             (date.getMonth() + 1).toString().padStart(2, '0') + '-' + 
             date.getDate().toString().padStart(2, '0') + ' ' +
             date.getHours().toString().padStart(2, '0') + ':' + 
             date.getMinutes().toString().padStart(2, '0')
    }
  }
}
</script>

<style>
/* 基础样式 - 兼容性更好 */
.article-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 15px;
  box-sizing: border-box;
}

.article-wrapper {
  background: #fff;
  box-shadow: 0 1px 3px rgba(0,0,0,0.1);
  margin: 20px 0;
  border-radius: 4px;
  overflow: hidden;
}

/* 文章头部样式 */
.article-header {
  padding: 25px 30px 15px;
  border-bottom: 1px solid #f0f0f0;
}

.article-title {
  font-size: 24px;
  line-height: 1.4;
  color: #333;
  margin: 0 0 15px;
  font-weight: 600;
}

.article-meta {
  font-size: 13px;
  color: #999;
  margin-bottom: 10px;
}

.meta-item {
  display: inline-block;
  margin-right: 20px;
  position: relative;
}

.meta-item i {
  margin-right: 5px;
}

/* 文章封面图 */
.article-cover {
  padding: 0 30px;
  margin: 20px 0;
}

.cover-image {
  max-width: 100%;
  height: auto;
  display: block;
  margin: 0 auto;
  border-radius: 4px;
}

/* 文章正文 */
.article-body {
  padding: 0 30px;
  line-height: 1.8;
  color: #333;
  font-size: 16px;
  word-wrap: break-word;
}

.article-body p {
  margin-bottom: 20px;
}

.article-body img {
  max-width: 100%;
  height: auto;
  display: block;
  margin: 15px auto;
  border-radius: 4px;
}

.article-body h2,
.article-body h3,
.article-body h4 {
  margin: 25px 0 15px;
  color: #333;
  font-weight: 600;
}

.article-body h2 {
  font-size: 22px;
  padding-bottom: 10px;
  border-bottom: 1px solid #f0f0f0;
}

.article-body h3 {
  font-size: 20px;
}

.article-body h4 {
  font-size: 18px;
}

.article-body blockquote {
  padding: 10px 15px;
  margin: 20px 0;
  background-color: #f8f9fa;
  border-left: 4px solid #ddd;
  color: #666;
  font-size: 15px;
}

.article-body pre {
  background-color: #f5f5f5;
  padding: 15px;
  border-radius: 4px;
  overflow-x: auto;
  margin: 15px 0;
  font-size: 14px;
}

.article-body code {
  font-family: Consolas, Monaco, 'Andale Mono', monospace;
  color: #c7254e;
  background-color: #f9f2f4;
  padding: 2px 4px;
  border-radius: 2px;
  font-size: 90%;
}

/* 文章页脚 */
.article-footer {
  padding: 20px 30px;
  border-top: 1px solid #f0f0f0;
  margin-top: 30px;
}

.article-tags {
  margin-top: 10px;
}

.tag-item {
  display: inline-block;
  padding: 3px 10px;
  margin-right: 8px;
  margin-bottom: 8px;
  font-size: 12px;
  color: #666;
  background-color: #f5f5f5;
  border-radius: 3px;
}

/* 评论区域 */
.comment-section {
  padding: 0 30px 30px;
  margin-top: 30px;
}

.comment-title {
  font-size: 18px;
  margin: 0 0 20px;
  padding-bottom: 10px;
  border-bottom: 1px solid #f0f0f0;
  position: relative;
}

.comment-title span {
  display: inline-block;
  padding-bottom: 10px;
  border-bottom: 2px solid #1890ff;
}

/* 评论列表 */
.comment-list {
  margin-bottom: 30px;
}

.comment-item {
  display: flex;
  padding: 15px 0;
  border-bottom: 1px dashed #eee;
}

.comment-avatar {
  width: 40px;
  height: 40px;
  margin-right: 15px;
  flex-shrink: 0;
}

.avatar-text {
  display: flex;
  width: 100%;
  height: 100%;
  background-color: #1890ff;
  color: #fff;
  border-radius: 50%;
  align-items: center;
  justify-content: center;
  font-weight: bold;
}

.comment-content {
  flex: 1;
}

.comment-header {
  margin-bottom: 8px;
  display: flex;
  justify-content: space-between;
}

.comment-user {
  font-weight: bold;
  color: #333;
}

.comment-time {
  font-size: 12px;
  color: #999;
}

.comment-text {
  font-size: 14px;
  line-height: 1.6;
  color: #333;
}

.no-comment {
  text-align: center;
  padding: 40px 0;
  color: #999;
}

.no-comment i {
  font-size: 40px;
  display: block;
  margin-bottom: 15px;
}

.no-comment p {
  margin: 0;
}

/* 评论表单 */
.comment-form {
  margin-top: 30px;
}

.form-title {
  font-size: 16px;
  margin-bottom: 15px;
  color: #333;
}

.form-group {
  margin-bottom: 15px;
}

.form-textarea {
  width: 100%;
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 4px;
  resize: vertical;
  min-height: 100px;
  font-size: 14px;
  box-sizing: border-box;
}

.form-textarea:focus {
  border-color: #1890ff;
  outline: none;
}

.form-row {
  display: flex;
  margin: 0 -10px;
}

.form-col {
  flex: 1;
  padding: 0 10px;
}

.form-input {
  width: 100%;
  padding: 8px 10px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 14px;
  box-sizing: border-box;
}

.form-input:focus {
  border-color: #1890ff;
  outline: none;
}

.submit-btn {
  width: 100%;
  padding: 8px 15px;
  background-color: #1890ff;
  color: #fff;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
}

.submit-btn:hover {
  background-color: #40a9ff;
}

/* 图标样式 - 使用伪元素实现，兼容性好 */
.icon-user:before {
  content: "👤";
}

.icon-source:before {
  content: "🏢";
}

.icon-date:before {
  content: "📅";
}

.icon-view:before {
  content: "👀";
}

.icon-comment:before {
  content: "💬";
}

/* 响应式设计 */
@media (max-width: 768px) {
  .article-header,
  .article-cover,
  .article-body,
  .article-footer,
  .comment-section {
    padding-left: 15px;
    padding-right: 15px;
  }
  
  .article-title {
    font-size: 20px;
  }
  
  .form-row {
    flex-wrap: wrap;
  }
  
  .form-col {
    flex: 100%;
    margin-bottom: 10px;
  }
  
  .form-col:last-child {
    margin-bottom: 0;
  }
}
</style>